package hsl.study.v1;


import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author HSL
 * @version 1.0
 * @data 2025/11/17 9:51
 * @desc 动态代理类
 */

public class ProxyHandler implements InvocationHandler {

    // 构建被代理的真实对象
    private Object target;

    // 构造方法注入
    public ProxyHandler(Object target) {
        this.target = target;
    }

    // 创建代理对象
    public Object getProxyInstance() {
        ClassLoader loader = target.getClass().getClassLoader();
        Class<?>[] interfaces = target.getClass().getInterfaces();
        InvocationHandler h = this;

        return Proxy.newProxyInstance(loader, interfaces, h);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("[代理前]执行方法:" + method.getName());

        Object result = method.invoke(target, args);
        System.out.println("[代理后]执行方法完毕");
        return result;
    }
}
